package root.electronclass.electronclass.personal.fragment.attendance

import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.bundleOf
import androidx.core.view.forEachIndexed
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import root.electronclass.electronclass.R
import root.electronclass.electronclass.adapter.GridSpacingItemDecoration
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.BasicDialogFragment
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.common.util.ToastUtil
import root.electronclass.electronclass.databinding.FragmentClassHomeworkStatisticalSubjectItemBinding
import root.electronclass.electronclass.databinding.FragmentPersonalAttendanceBinding
import root.electronclass.electronclass.databinding.FragmentPersonalAttendanceItemBinding
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.ext.tabs
import root.electronclass.electronclass.grade.model.AttendanceReport
import root.electronclass.electronclass.grade.model.PersonalAttendanceStatQuery
import root.electronclass.electronclass.mvp.base.data
import root.electronclass.electronclass.mvp.base.isSuccessful
import root.electronclass.electronclass.mvp.rest.ClassApi

/**
 * 个人考勤页面
 * @author Lokiy
 * @date 2023/3/22 23:30
 */
class PersonalAttendanceFragment : ViewBindingFragment<FragmentPersonalAttendanceBinding>() {

    private var pageIndex = 1
    private var type = 1 //1-7天 2-一个月 3-一学期

    private val itemsAdapter = BasicAdapter<AttendanceReport, FragmentPersonalAttendanceItemBinding>(onLoadMore = { getData() }) { holder, item ->
        holder.binding.root.backgroundTintList = ColorStateList.valueOf(if (holder.adapterPosition % 2 == 0) 0 else 0xfF7f8f9)
        holder.binding.itemDate.text = item.statDate
        holder.binding.itemMorning.text = item.getSignText(item.morningStatus)
        holder.binding.itemNoon.text = item.getSignText(item.noonStatus)
        holder.binding.itemAfternoon.text = item.getSignText(item.afternoonStatus)
        holder.binding.itemDetail.text = "查看"
        holder.binding.itemDetail.setTextColor(resources.getColor(R.color.c_brand))
        holder.binding.itemDetail.setOnClickListener {
            lifecycleScope.launch(CoroutineExceptionHandler { dismissProgress() }) {
                val response = withContext(Dispatchers.IO) {
                    ClassApi.service.getStudentAttnDetail(item.id)
                }
                dismissProgress()
                if (response.isSuccessful && response.data.isNotEmpty()) {
                    PersonalAttendanceDetailDialog().apply {
                        arguments =
                            bundleOf(
                                BasicDialogFragment.CLOSE to true,
                                BasicDialogFragment.TITLE to "考勤详情",
                                EXTRA_DATA to response.data[0].apply {
                                    urls = response.data.map { it.picUrl }.toTypedArray()
                                })
                    }.show(childFragmentManager, "PADD")
                } else {
                    ToastUtil.showToast(requireActivity(), "获取签到详情失败，请稍后重试")
                }
            }
        }
    }

    private val subjectAdapter = BasicAdapter<Pair<String, Int>, FragmentClassHomeworkStatisticalSubjectItemBinding> { holder, item ->
        holder.binding.itemSubject.text = item.first
        holder.binding.itemCount.text = item.second.toString()
        (holder.binding.itemSubject.parent as View).setBackgroundResource(
            if (item.first.contains("假")) R.drawable.ic_attendance_1 else R.drawable.ic_attendance_2
        )
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val tabs = resources.getStringArray(R.array.person_tabs)
        binding.tabLayout.tabs(tabs) {
            type = tabs.indexOf(it) + 1
            pageIndex = 1
            getData()
        }
        binding.studentRecyclerTitle.root.apply {
            val names = resources.getStringArray(R.array.personal_attendance_titles)
            forEachIndexed { index, it ->
                val view1: View
                if (it is TextView) {
                    view1 = it
                } else {
                    it as ViewGroup
                    view1 = it.getChildAt(0)
                    view1 as TextView
                }
                view1.setTextColor(0xFFFFFFFF.toInt())
                view1.text = names[index]
            }
            updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = 56
            }
        }
        binding.itemRecycler.adapter = itemsAdapter
        binding.subjectRecycler.addItemDecoration(GridSpacingItemDecoration(2, 30, true))
        binding.subjectRecycler.adapter = subjectAdapter
        getData()
    }

    private fun getData() {
        if (pageIndex == 1) {
            lifecycleScope.launch(CoroutineExceptionHandler()) {
                val type = type
                val response = withContext(Dispatchers.IO) {
                    ClassApi.service.getStudentAttnStat(type)
                }
                if (response.isSuccessful) {
                    val list = mutableListOf<Pair<String, Int>>()
                    list.add(Pair("病假", response.data.sickLeave))
                    list.add(Pair("事假", response.data.compassionateLeave))
                    list.add(Pair("其他请假", response.data.other))

                    val list1 = mutableListOf<Pair<String, Int>>()
                    list1.add(Pair("迟到", response.data.late))
                    list1.add(Pair("早退", response.data.leaveEarly))
                    list1.add(Pair("旷课", response.data.truancy))
                    subjectAdapter.addAll(list.sortedBy { -it.second }
                        .filter { it.second > 0 } + list1.sortedBy { -it.second }
                        .filter { it.second > 0 })
                    binding.actualDay.text = response.data.actualDay.toString()
                    binding.totalDay.text = response.data.totalDay.toString()
                    binding.statTitle.text =
                        "%s考勤统计".format(if (type == 1) "近7天" else if (type == 2) "近3个月" else "本学期")
                }
            }
        }
        lifecycleScope.launch(CoroutineExceptionHandler { dismissProgress() }) {
            val response = withContext(Dispatchers.IO) {
                ClassApi.service.getStudentAttnList(PersonalAttendanceStatQuery(pageIndex, type))
            }
            dismissProgress()
            if (response.isSuccessful) {
                if (pageIndex == 1) {
                    itemsAdapter.notifyChanged(response!!.rows.records)
                } else {
                    itemsAdapter.addAll(response!!.rows.records)
                }
                pageIndex++
            }
        }
    }

}